package com.hankol.community.fragment

import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.adapter.StateViewPagerAdapter
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.utils.StatusBarUtil.setStatusBarDarkTheme
import com.baselibrary.utils.StatusBarUtil.setStatusBarHeight
import com.baselibrary.activity.BaseFragment
import com.hankol.community.R
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.databinding.FragmentMainHomeBinding
import com.hankol.community.viewmodel.CommunityViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 *@author:hanke
 *2022/3/30
 *desc:
 */
class CommunityHomeFragment : BaseFragment(), View.OnClickListener {
    private lateinit var mBinding: FragmentMainHomeBinding
    private lateinit var mViewModel: CommunityViewModel
    private val mTitleArr = arrayOf("关注", "发现", "视频")
    private var leavePos = -1 //记录离开界面时 所显示的界面索引
    val communityHelp: CommunityHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)
    private var selectedPosition = 0;
    private val fragments = ArrayList<Fragment>()

    companion object {
var currTab =0;
        fun newInstance(): CommunityHomeFragment {
            return CommunityHomeFragment()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_main_home
    }

    override fun init() {
        initView()
        initListener()
        addObserver()
        loadHotWord()
        SensorsDataManager.instance.setWineryDynamicPagePos("社区发现页")

    }

    private fun initView() {
        mBinding = getDataBinding<FragmentMainHomeBinding>()
        mViewModel = getFragmentViewModelProvider(this).get(CommunityViewModel::class.java)
        setStatusBarHeight(mBinding.root, activity)
        setStatusBarDarkTheme(activity, true)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        fragments.add(CommunityFollowFragment.newInstance())
        fragments.add(CommunityDiscoverFragment.newInstance())
        fragments.add(CommunityVideoFragment.newInstance())
        try {
            mBinding.viewPager.adapter = StateViewPagerAdapter(fragmentManager, fragments)
            mBinding.stlMain.setViewPager(mBinding.viewPager, mTitleArr)
            mBinding.stlMain.setShowIndicator(true)
            mBinding.viewPager.currentItem = 1
            selectedPosition = 1
            mBinding.viewPager.offscreenPageLimit = fragments.size
            mBinding.viewPager.addOnPageChangeListener(object : OnPageChangeListener {
                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                    if (position == 1&&mBinding.viewPager.currentItem!=0) {
                        EventBusUtils.sendNotify1Value(MessageBus.msgId_switch_video_page_offset, positionOffset)
                    }
                }
                override fun onPageSelected(position: Int) {
                    currTab=position
                    selectedPosition = position
                    if (position == 2) {
                        mBinding.ivGoMessage.setImageResource(R.drawable.ic_go_message_white)
                    } else {
                        mBinding.ivGoMessage.setImageResource(R.drawable.ic_go_message)
                    }
                    if (position == 0) {
                        (fragments[0] as CommunityFollowFragment).controlVideo(true)
                    } else {
                        (fragments[0] as CommunityFollowFragment).controlVideo(false)
                    }
                }

                override fun onPageScrollStateChanged(state: Int) {}
            })
            mBinding.stlMain.updateTabSelection(selectedPosition)
        } catch (e: Exception) {
        }
        isShowScanCode()
    }

    private fun initListener() {
        mBinding.ivGoMessage.setOnClickListener(this)
        mBinding.rlSearch.setOnClickListener(this)
        mBinding.tvSearch.setOnClickListener(this)
    }
    val searchKeyList = mutableListOf<String>()
    private fun addObserver() {
        mViewModel.hotWordListLD.observe(viewLifecycleOwner, Observer { it ->
            searchKeyList.clear()
                for (data in it) {
                    searchKeyList.add(data.name)
                }
                initSearch(searchKeyList)
        })
    }


    private fun loadHotWord() {
        mViewModel.reqGetHotWordList(0)
    }

    private fun initSearch(searchKeyList: MutableList<String>) {
        //滚动的评论
        mBinding.marqueeView.removeAllViews()
        mBinding.marqueeView.isAutoStart = false
        for (evaluateBean in searchKeyList) {
            val inflateView = View.inflate(requireContext(), R.layout.view_evaluate_layout, null)
            val tvContent = inflateView.findViewById<TextView>(R.id.tv_evaluate)
            tvContent.text = evaluateBean.checkValue()
            tvContent.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_D8D8D8))
            tvContent.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14f)
            tvContent.setOnClickListener {
                //打开搜索
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    val bundle = Bundle()
                    bundle.putInt(IntentKey.SEARCH_TYPE, 0)
                    bundle.putString(IntentKey.SEARCH_KEY_WORD, evaluateBean.checkValue())
                    ActivityRouter.startActivity(ActivityRouter.ACTIVITY.SEARCH_ALL, bundle)
                }
            }
            mBinding.marqueeView.addView(inflateView)
        }
        mBinding.marqueeView.visibility = if (searchKeyList.size == 0) View.GONE else View.VISIBLE
        mBinding.tvSearch.visibility = if (searchKeyList.size == 0) View.VISIBLE else View.GONE
        if (searchKeyList.size > 1) {
            mBinding.marqueeView.startFlipping()
        } else {
            mBinding.marqueeView.stopFlipping()
        }
    }

    private fun isShowScanCode() {
        SpUtils.getInstance().putScanCodeNewIcon(false)
    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.iv_go_message -> goMessage()
            R.id.rl_search,R.id.tv_search -> goSearch()
        }
    }

    //去消息中心
    private fun goMessage() {
        if (!SpUtils.getInstance().isLogin) {
            AppManager.getAppManager().openLoginPage()
            return
        }
        if (!DoubleClickHelper.isOnDoubleClick()) {
            SensorsDataManager.instance.newsiconClick("首页")
            ARouterUtils.jump(ActivityRouter.MESSAGE.MESSAGE_MAIN_PAGE)
        }
    }

    private fun goSearch() {
        if (!DoubleClickHelper.isOnDoubleClick()) {
            val bundle = Bundle()
            bundle.putInt(IntentKey.SEARCH_TYPE, 0)
            ActivityRouter.startActivity(ActivityRouter.ACTIVITY.SEARCH_ALL, bundle)
        }
    }
    //刷新数据
    private fun refreshCurrentPageData() {
        when (mBinding.stlMain.currentTab) {
            0 -> (fragments[0] as CommunityFollowFragment).doRefresh()
            1 -> (fragments[1] as CommunityDiscoverFragment).doRefresh()
            2 -> (fragments[2] as CommunityVideoFragment).doRefresh()
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_home_alpha) {
            mBinding.rlTop.alpha = messageBus.message as Float
        } else if (messageBus.codeType == MessageBus.msgId_gray_mode) {
            //默哀模式
            val grayMode = messageBus.param1 as Int
            if (grayMode == 1) {
//                GrayUtils.setColorThemeMode(mBinding.rlTopTitle)
            }
        } else if (messageBus.codeType == MessageBus.msgId_app_style) {
            //节日客户端 导航条 样式切换
            val appStyle = messageBus.param1 as Int
        } else if (messageBus.codeType == MessageBus.msgId_remove_video_red_point) {
            mBinding.stlMain.setShowRedDot(false)
            mBinding.stlMain.updateTabSelection(selectedPosition)
        } else if (messageBus.codeType == MessageBus.msgId_unread_msg_cnt) {
            showRed(messageBus.message as String)
        } else if (messageBus.codeType == MessageBus.msgId_set_scroll) {
            mBinding.viewPager.isCanSlide = messageBus.param1 as Boolean
        } else if (messageBus.codeType == MessageBus.msgId_refresh_cummunity) {
            refreshCurrentPageData()
        }
    }

    private fun showRed(amount: String) {
        if (amount != "0") {
            mBinding.tvMessageNoRead.visibility = View.VISIBLE
            mBinding.tvMessageNoRead.text = amount
            val params = mBinding.tvMessageNoRead.layoutParams
            //获取view的margin设置参数
            var marginParams: ViewGroup.MarginLayoutParams? = if (params is ViewGroup.MarginLayoutParams) {
                params
            } else {
                ViewGroup.MarginLayoutParams(params)
            }
            if (amount != "99+") {
                marginParams?.setMargins(0, ScreenUtils.dpToPx(7), ScreenUtils.dpToPx(14), 0)
                mBinding.tvMessageNoRead.setBackgroundResource(R.drawable.shape_f54d53_solid_circle)
            } else {
                marginParams?.setMargins(0, ScreenUtils.dpToPx(7), ScreenUtils.dpToPx(8), 0)
                mBinding.tvMessageNoRead.setBackgroundResource(R.drawable.shape_f54d53_solid_oval)
            }

        } else {
            mBinding.tvMessageNoRead.visibility = View.INVISIBLE
        }
    }

    override fun onDestroyView() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroyView()
    }

    //底部点击首页tab 回调
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            EventBusUtils.sendNotify1Value(MessageBus.msgId_current_playing_video_page,mBinding.stlMain.currentTab == 2)
            SpUtils.putBoolean(requireContext(), Constants.KEY_CURRENT_IS_VIDEO_PAGE, mBinding.stlMain.currentTab == 2)
            mBinding.marqueeView.stopFlipping()
            //此处是控制切换底部tab是 社区的浏览时长统计 以及 关注页面的视频暂停与播放
            when (mBinding.stlMain.currentTab) {
                0 -> {
                    (fragments[0] as CommunityFollowFragment).userVisibleHint = false
                    (fragments[0] as CommunityFollowFragment).controlVideo(false)
                }
                1 -> (fragments[1] as CommunityDiscoverFragment).userVisibleHint = false
                2 -> (fragments[2] as CommunityVideoFragment).userVisibleHint = false
            }
        } else {
            SpUtils.putBoolean(requireContext(), Constants.KEY_CURRENT_IS_VIDEO_PAGE, mBinding.viewPager.currentItem == 2)
            EventBusUtils.sendNotify1Value(MessageBus.msgId_current_playing_video_page,mBinding.viewPager.currentItem == 2)
            if (mBinding.viewPager.currentItem == 2) {
                (fragments[2] as CommunityVideoFragment).userVisibleHint = !hidden
            }
            if(searchKeyList.size>1) {
                mBinding.marqueeView.startFlipping()
            }
            if (mBinding.stlMain.currentTab == 0) {
                (fragments[0] as CommunityFollowFragment).controlVideo(true)
            }
        }
    }

    fun goFollow() {
        mBinding.viewPager.currentItem = 0
    }
    fun getCurrentTap():Int{
        return mBinding.viewPager.currentItem;
    }
}